class SocketService {
  static instance: SocketService | null = null;

  private ws: WebSocket | null = null;

  private callBackMapping: Record<string, Function> = {};

  connected = false;

  sendRetryCount = 0;

  connectRetryCount = 0;

  url = "ws://localhost:8080"; // 假设这个URL是经过安全检查的

  private sendFixHeartTimer: NodeJS.Timeout | null = null;

  private constructor() {
    // 私有构造函数，确保单例模式
  }

  registerCallback(type: string, callback: (data: any) => void): void {
    this.callBackMapping[type] = callback;
  }

  static get Instance() {
    if (!SocketService.instance) {
      SocketService.instance = new SocketService();
    }
    return SocketService.instance;
  }

  sendFixHeart() {
    if (this.ws && this.connected) {
      clearInterval(this.sendFixHeartTimer);
      this.sendFixHeartTimer = setInterval(() => {
        if (this.ws?.readyState === WebSocket.OPEN) {
          this.ws.send(JSON.stringify({ push_type: "ping" }));
        }
      }, 20000);
    }
  }

  connect() {
    if (!window.WebSocket) {
      console.log("您的浏览器不支持WebSocket");
      return;
    }

    this.ws = new WebSocket(this.url);

    this.ws.onopen = () => {
      console.log("连接服务端成功了,ws状态是" + this.ws?.readyState);
      this.connected = true;
      this.connectRetryCount = 0;
      this.sendFixHeart();
    };

    this.ws.onmessage = (event: MessageEvent<string>) => {
      try {
        const data = JSON.parse(event.data);
        let object_name = "";
        if (data.object_name == "textMessage") {
          object_name = "textMessage";
        }
        // 安全地调用回调函数
        return this.callBackMapping[object_name](data);
      } catch (error) {
        // 区分不同类型的错误
        if (error instanceof SyntaxError) {
          console.error("解析消息数据出错: JSON格式错误", error);
        } else {
          console.error("解析消息数据出错: 其他错误", error);
        }
      }
    };

    this.ws.onclose = () => {
      this.connected = false;
      if (this.connectRetryCount < 10) {
        this.connectRetryCount++;
        setTimeout(() => {
          console.log(
            "连接服务端失败第" + this.connectRetryCount + "次，1秒后重试"
          );
          this.connect();
        }, 3000 * this.connectRetryCount); // 使用退避策略增加重试间隔
      } else {
        console.log("重新连接服务器失败");
        this.ws?.close();
      }
    };

    this.ws.onerror = (error: ErrorEvent) => {
      console.error("Error，websocket连接错误:", error);
    };
  }

  textMessage(data: any) {
    console.log("发送消息");
  }

  send(data: Record<string, any>) {
    if (this.connected) {
      this.sendRetryCount = 0;
      if (this.ws?.readyState === WebSocket.OPEN) {
        this.ws.send(JSON.stringify(data));
      }
    } else {
      this.sendRetryCount++;
      setTimeout(() => {
        this.send(data);
        console.log("已经重新发送第:" + this.sendRetryCount + "次");
      }, 3000);
    }
  }

  close() {
    if (this.sendFixHeartTimer) clearInterval(this.sendFixHeartTimer);
    if (this.ws) this.ws.close();
  }
}

export default SocketService;
